<template>
  <!-- 角色查询 -->
  <el-row>
    <el-col :span="24">
      <el-card
        class="box-card"
        id="card"
        v-loading="loading"
        element-loading-text="拼命加载中"
        element-loading-background="rgb(255,255,255)"
      >
        <div slot="header" class="clearfix">
          <span>部门管理</span>
          <span
            >-您可以通过搜索或者其他的筛选项对部门的信息进行编辑、删除等管理操作。^_^</span
          >
        </div>

        <!-- 表单显示 -->
        <el-row type="flex">
          <div :span="12">
            <div class="custom-tree-container">
              <div class="block">
                <el-tree
                  :data="data"
                  show-checkbox
                  node-key="id"
                  :expand-on-click-node="false"
                  @node-click="handleNodeClick"
                  accordion
                  ref="tree"
                >
                  <span class="custom-tree-node" slot-scope="{ node, data }">
                    <span class="menuText">{{ node.label }}</span>
                    <span>
                      <template
                        v-if="
                          data.children != null && data.children != undefined
                        "
                      >
                        <el-button
                          type="text"
                          size="mini"
                          style="color:rgb(103,194,58)"
                          @click="() => append(data)"
                        >
                          添加
                        </el-button>
                      </template>

                      <el-button
                        type="text"
                        size="mini"
                        @click="() => modify(node, data)"
                      >
                        修改
                      </el-button>

                      <el-button
                        type="text"
                        size="mini"
                        style="color:rgb(245,108,108)"
                        @click="() => remove(node, data)"
                      >
                        删除
                      </el-button>
                    </span>
                  </span>
                </el-tree>
              </div>
            </div>
          </div>

          <!-- 新增部门对话框 -->
          <el-dialog
            title="添加部门"
            :visible.sync="dialogVisible"
            width="30%"
            :before-close="handleClose"
          >
            <div class="addDepartment">部门名称</div>
            <el-input
              v-model="addDepartment.departmentName"
              placeholder="请输入部门"
            ></el-input>
            <div class="addDepartment">科目名称</div>
            <el-input
              v-model="addDepartment.subjectName"
              minlength="2"
              maxlength="8"
              placeholder="请输入科目"
              show-word-limit
            ></el-input>
            <div class="addDepartment">部门说明</div>
            <el-input
              type="textarea"
              :rows="2"
              placeholder="请输入内容"
              v-model="addDepartment.departmentExplain"
            >
            </el-input>
            <span slot="footer" class="dialog-footer">
              <el-button @click="dialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="submitAdd">确 定</el-button>
            </span>
          </el-dialog>

          <el-col :span="3">
            <el-button
              type="success"
              class="operationButton"
              @click="dialogVisible = true"
              plain
              >添加部门</el-button
            >
            <el-button
              type="warning"
              class="operationButton"
              @click="secondLevelDelete"
              plain
              >删除多个</el-button
            >
          </el-col>
          <el-col :span="9">
            <el-row
              type="flex"
              justify="center"
              class="updateDepartmentExplain"
            >
              <el-input
                type="textarea"
                :rows="8"
                placeholder="请输入内容"
                v-model="modifydDepartment.departmentExplain"
              >
              </el-input>
            </el-row>

            <el-row type="flex" justify="center">
              <el-button type="info" @click="updateData" plain
                >更新数据</el-button
              >
            </el-row>
          </el-col>
        </el-row>
      </el-card>
    </el-col>
  </el-row>
</template>

<script>
let id = 1000;
export default {
  data() {
    let data = [];
    return {
      data: JSON.parse(JSON.stringify(data)),
      data: JSON.parse(JSON.stringify(data)),
      loading: false,
      dialogVisible: false,
      addDepartment: {
        departmentName: "",
        departmentExplain: "",
        subjectName: ""
      },
      modifydDepartment: {
        departmentId: "",
        departmentExplain: "",
        departmentName: "",
        children: []
      }
    };
  },
  methods: {
    /**
     * 添加
     */
    append(data) {
      //输入部门/科目名称
      this.$prompt("请输入 科目 名称", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        // 匹配中文，英文字母和数字及_:
        inputPattern: /[\u4e00-\u9fa5_a-zA-Z0-9_]{2,8}/,
        inputErrorMessage: "名称支持 【中文，英文字母和数字及_】长度为2·8"
      })
        .then(({ value }) => {
          //保存数据到数据库
          this.$axios
            .get("/api/biz/subject/add", {
              params: {
                departmentId: data.id,
                subjectName: value
              }
            })
            .then(result => {
              let resultData = result.data;
              if (resultData.code == 0) {
                console.log();
                //生成前端数据
                const newChild = {
                  id: resultData.data.subjectId,
                  label: value,
                  children: null
                };
                if (!data.children) {
                  this.$set(data, "children", []);
                }
                //数据追加
                data.children.push(newChild);
                this.$message({
                  type: "success",
                  message: "新增成功"
                });
              } else {
                this.$message({
                  type: "error",
                  message: "新增科目失败！"
                });
              }
            })
            .catch(err => {
              this.$message({
                type: "error",
                message: err
              });
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消输入"
          });
        });
    },

    /**
     * 删除
     */
    remove(node, data) {
      this.$confirm("此操作将永久删除该部门/科目, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          let dataArray = [];
          dataArray.push(data);
          this.delete(dataArray);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });

      // this.$axios
      //   .get("/api/biz/subject/del/" + data.id)
      //   .then(result => {
      //     let data = result.data;
      //     if (data.code == 0) {
      //       this.$message({
      //         type: "success",
      //         message: "删除成功！"
      //       });
      //       const parent = node.parent;
      //       const children = parent.data.children || parent.data;
      //       const index = children.findIndex(d => d.id === data.id);
      //       children.splice(index, 1);
      //     } else {
      //       this.$message({
      //         type: "error",
      //         message: "删除失败！"
      //       });
      //     }
      //   })
      //   .catch(err => {
      //     this.$message({
      //       type: "error",
      //       message: err
      //     });
      //   });
    },

    /**
     * 修改
     */
    modify(node, data) {
      this.$prompt("请输入要修改的 科目 名称", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        // 匹配中文，英文字母和数字及_:
        inputPattern: /[\u4e00-\u9fa5_a-zA-Z0-9_]{2,8}/,
        inputErrorMessage: "名称支持 【中文，英文字母和数字及_】长度为2·8"
      })
        .then(({ value }) => {
          //科目
          if (data.children == undefined || data.children == null) {
            this.$axios
              .get("/api/biz/subject/modify", {
                params: {
                  id: data.id,
                  subjectName: value,
                  subjectExplain: this.modifydDepartment.departmentExplain
                }
              })
              .then(result => {
                let resultData = result.data;
                if (resultData.code == 0) {
                  //对前端数据进行修改
                  const parent = node.parent;
                  const children = parent.data.children || parent.data;
                  const index = children.findIndex(d => d.id === data.id);
                  children[index].label = value;
                  children.splice(index, 1, children[index]);

                  this.$message({
                    type: "success",
                    message: "修改成功"
                  });
                } else {
                  this.$message({
                    type: "error",
                    message: "修改失败！"
                  });
                }
              })
              .catch(err => {
                this.$message({
                  type: "error",
                  message: err
                });
              });
          }
          //部门
          else {
            console.log(data.id);
            this.$axios
              .post("/api/biz/department/modify", {
                departmentId: data.id,
                departmentName: value,
                departmentExplain: this.modifydDepartment.departmentExplain
              })
              .then(result => {
                let resultData = result.data;
                if (resultData.code == 0) {
                  //对前端数据进行修改
                  const parent = node.parent;
                  const children = parent.data.children || parent.data;
                  const index = children.findIndex(d => d.id === data.id);
                  children[index].label = value;
                  children.splice(index, 1, children[index]);

                  this.$message({
                    type: "success",
                    message: "修改成功"
                  });
                } else {
                  this.$message({
                    type: "error",
                    message: "修改失败！"
                  });
                }
              })
              .catch(err => {
                this.$message({
                  type: "error",
                  message: err
                });
              });
          }
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "取消输入"
          });
        });
    },
    /**
     * 通过 node 获取
     */
    getCheckedNodes() {
      return this.$refs.tree.getCheckedNodes();
    },

    /**
     * 多选删除
     */
    secondLevelDelete() {
      this.$confirm("此操作将永久删除该部门/科目, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.delete(undefined);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },

    /**
     * 删除
     */
    delete(radioDelete) {
      let nodes = undefined;
      //单选删除
      if (
        radioDelete == undefined ||
        radioDelete == null ||
        radioDelete == ""
      ) {
        nodes = this.getCheckedNodes();
      } else {
        nodes = radioDelete;
      }

      if (nodes.length == 0 || nodes == undefined) {
        this.$message({
          type: "error",
          message: "未选择部门或科目"
        });
        return false;
      }

      this.$axios
        .post("/api/biz/department/secondLevelDelete", nodes)
        .then(result => {
          let data = result.data;
          if (data.code == 0) {
            //删除前端数据
            for (let i = 0; i < nodes.length; i++) {
              let node = nodes[i].children;

              //选择的父科目
              if (node != undefined) {
                //父科目
                for (let h = 0; h < this.data.length; h++) {
                  if (this.data[h].id == nodes[i].id) {
                    this.data.splice(h, 1);
                  }
                }
              }
              //选择的子科目
              else {
                //子科目
                for (let h = 0; h < this.data.length; h++) {
                  for (let e = 0; e < this.data[h].children.length; e++) {
                    if (this.data[h].children[e].id == nodes[i].id) {
                      this.data[h].children.splice(e, 1);
                    }
                  }
                }
              }
            }

            this.$message({
              type: "success",
              message: "删除成功！"
            });
          } else {
            this.$message({
              type: "error",
              message: "删除出现错误"
            });
          }
        })
        .catch(err => {
          this.$message({
            type: "error",
            message: err
          });
        });
    },

    /**
     * 添加部门
     */
    submitAdd() {
      if (
        this.addDepartment.subjectName.length < 2 ||
        this.addDepartment.subjectName.length > 8 ||
        this.addDepartment.departmentName.length < 2 ||
        this.addDepartment.departmentName.length > 8
      ) {
        this.$message({
          type: "error",
          message: "部门和科目不能为空，并且长度到2·8之间"
        });
        return false;
      }
      this.$axios
        .post("/api/biz/department/add", this.addDepartment)
        .then(result => {
          let data = result.data;
          if (data.code == 0) {
            //添加成功
            if (data.code == 0) {
              let resultData = data.data;

              let childrens = [];

              childrens.push({
                id: resultData.subjectDTOS[0].subjectId,
                label: resultData.subjectDTOS[0].subjectName
              });

              this.data.push({
                id: resultData.departmentId,
                label: resultData.departmentName,
                children: childrens
              });

              this.dialogVisible = false;
              this.$message({
                type: "success",
                message: "保存成功！"
              });
            } else {
              //添加失败
              this.$message({
                type: "error",
                message: "添加失败！"
              });
            }
          } else {
            this.$message({
              type: "error",
              message: "保存失败！"
            });
          }
        })
        .catch(err => {
          this.$message({
            type: "error",
            message: err
          });
        });
    },
    /**
     * 关闭对话框
     */
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then(_ => {
          done();
        })
        .catch(_ => {});
    },
    /**
     * 部门说明
     */
    handleNodeClick(data) {
      this.modifydDepartment.departmentId = data.id;
      this.modifydDepartment.departmentName = data.label;
      this.modifydDepartment.departmentExplain = data.explain;
      this.modifydDepartment.children = data.children;
    },
    /**
     * 更新说明
     */
    updateData() {
      console.log();
      if (
        this.modifydDepartment.departmentId == undefined ||
        this.modifydDepartment.departmentId == null ||
        this.modifydDepartment.departmentId == ""
      ) {
        this.$message.error("未选择部门/科目");
      }
      //部门
      else if (
        this.modifydDepartment.children != undefined &&
        this.modifydDepartment.children != null
      ) {
        this.$axios
          .post("/api/biz/department/modify", {
            departmentId: this.modifydDepartment.departmentId,
            departmentName: this.modifydDepartment.departmentName,
            departmentExplain: this.modifydDepartment.departmentExplain
          })
          .then(result => {
            let data = result.data;
            if (data.code == 0) {
              for (let i = 0; i < this.data.length; i++) {
                if (this.modifydDepartment.departmentId == this.data[i].id) {
                  this.data[
                    i
                  ].explain = this.modifydDepartment.departmentExplain;
                }
              }
              this.$message.success("更新成功");
            } else {
              this.$message.error("更新失败");
            }
          })
          .catch(err => {
            this.$message.error(err);
          });
      }
      //科目
      else {
        this.$axios
          .get("/api/biz/subject/modify", {
            params: {
              id: this.modifydDepartment.departmentId,
              subjectName: this.modifydDepartment.departmentName,
              subjectExplain: this.modifydDepartment.departmentExplain
            }
          })
          .then(result => {
            let data = result.data;
            if (data.code == 0) {
              for (let i = 0; i < this.data.length; i++) {
                for (let j = 0; j < this.data[i].children.length; j++) {
                  if (
                    this.modifydDepartment.departmentId ==
                    this.data[i].children[j].id
                  ) {
                    this.data[i].children[
                      j
                    ].explain = this.modifydDepartment.departmentExplain;
                  }
                }
              }

              this.$message.success("更新成功");
            } else {
              this.$message.error("更新失败");
            }
          })
          .catch(err => {
            this.$message.error(err);
          });
      }
    }
  },

  /**
   * 页面初始化时执行
   */
  mounted() {
    this.loading = true;
    //获取部门信息
    this.$axios
      .get("/api/biz/department/subject", {
        headers: { Authorization: sessionStorage.getItem("token") }
      })
      .then(result => {
        let data = result.data;
        if (data.code == 0) {
          let text = data.data;
          //一级菜单循环
          for (var i = 0; i < text.length; i++) {
            let childrens = [];
            if (
              text[i].subjectDTOS != undefined &&
              text[i].subjectDTOS != null &&
              text[i].subjectDTOS != ""
            ) {
              // 二级菜单循环
              for (var j = 0; j < text[i].subjectDTOS.length; j++) {
                if (text[i].subjectDTOS[j].subjectId != null) {
                  childrens.push({
                    id: text[i].subjectDTOS[j].subjectId,
                    label: text[i].subjectDTOS[j].subjectName,
                    explain: text[i].subjectDTOS[j].subjectExplain
                  });
                }
              }
            }

            this.data.push({
              id: text[i].departmentId,
              label: text[i].departmentName,
              explain: text[i].departmentExplain,
              children: childrens
            });
          }
        } else {
          this.$message.error(data.msg);
        }
        this.loading = false;
      })
      .catch(err => {
        this.$message.error(err);
      });
  }
};
</script>

<style scoped>
#card {
  width: 100%;
  margin: 0px;
}
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
  border-bottom: 1px solid #ebeef5;
}
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}
.clearfix {
  text-align: left;
}
.clearfix > span:last-child {
  color: #333333;
  font-size: 13px;
}
.clearfix > span:first-child {
  font-weight: bold;
  color: #59a6f5;
  margin-right: 20px;
}
.queryButton {
  padding-bottom: 20px;
}
.pagination {
  padding-top: 20px;
}

.el-form-item__content {
  margin-left: 100px;
  margin-right: 50px;
}
.el-select {
  width: 100%;
}
.el-dialog__body {
  padding-top: 10px;
}
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
.menuText {
  padding-right: 200px;
}
.operationButton {
  margin-left: 0px;
  margin-bottom: 10px;
}
.addDepartment {
  margin: 10px 0px;
}
.updateDepartmentExplain {
  margin-bottom: 20px;
}
</style>
